// 导入defineStore方法
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { buyProducts } from '../api/product'
import { ElMessage } from 'element-plus'

// 创建并导出store
export const useShoppingCarStore = defineStore('carStore', () => {
  const carList = ref([]) // 购物车列表
  const products = ref([]) // 商品列表
  const totalPrice = computed(() => {
    let sum = 0
    if (carList.value.length !== 0) {
      carList.value.forEach((item) => {
        sum += item.price * item.number
      })
    }
    return sum
  }) // 总价
  const addToCart = (data) => {
    if (data.number == 0) {
      ElMessage({
        message: '没有库存咯',
        type: 'error'
      })
    } else {
      data.number--
      if (carList.value.some((item) => item.id === data.id)) {
        const i = carList.value.findIndex((item) => item.id === data.id)
        carList.value[i].number++
      } else {
        carList.value.push({
          id: data.id,
          title: data.title,
          price: data.price,
          number: 1
        })
        carList.value.sort((a, b) => a.id - b.id)
      }
    }
  } // 添加商品到购物车
  const clearCar = () => {
    buyProducts().then((res) => {
      console.log(res)
      if (res) {
        ElMessage.success('清空成功')
        carList.value = []
      } else {
        ElMessage.error('清空失败')
      }
    })
  } // 清空购物车

  return {
    carList,
    totalPrice,
    products,
    addToCart,
    clearCar
  }
})
